package com.lagou.controller;

import com.lagou.dao.UserDao;
import com.lagou.pojo.User;
import com.lagou.service.CodeService;
import com.lagou.service.UserService;
import com.netflix.client.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private CodeService codeService;

    @Autowired
    private UserService userService;

    @RequestMapping("/register/{email}/{password}/{code}")
    public boolean register(HttpServletResponse response, @PathVariable String email, @PathVariable String password, @PathVariable String code){
        int validate = codeService.validate(email, code);
        if(validate!=0){
            return false;
        }
        //存储用户名和密码
        String token = userService.insertUser(email, password);
        Cookie cookie = new Cookie("token",token);
        response.addCookie(cookie);
        return true;
    }

    @RequestMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable String email){
        User user = userService.selectUser(email);
        if(user != null){
            return true;
        }
        return false;
    }

    @RequestMapping("/login/{email}/{password}")
    public String login(HttpServletResponse response, @PathVariable String email, @PathVariable String password){
        String token = userService.validate(email, password);
        if("".equals(token)){
            return "false";
        }
        Cookie cookie = new Cookie("token", token);
        response.addCookie(cookie);
        return token;
    }
}
